package org.hdl.anima.proxy;

import static com.google.common.base.Preconditions.checkArgument;

import org.hdl.anima.AppConf;
import org.hdl.anima.Application;
import org.hdl.anima.message.IMessage;
import org.hdl.anima.message.MessageBinWrap;
import org.hdl.anima.message.MessageObjWrap;
import org.hdl.anima.transport.ChannelHandler;
import org.hdl.anima.transport.Codec;
import org.hdl.anima.transport.RemoteException;
import org.hdl.anima.transport.Transporters;
import org.hdl.anima.transport.support.AbstractClient;
/**
 * 
 * @author qiuhd
 * @since  2014年8月13日
 */
public class ExchangeClient {

	private AbstractClient client ;
	private final ServerProxyConfig config;
	private final AppConf conf;
	
	public ExchangeClient(ServerProxy proxy,ChannelHandler handler,Codec codec) throws RemoteException {
		checkArgument(proxy != null,"serverProxy == null");
		this.config = proxy.getConifg();
		this.conf = proxy.getAppConf();
		client  = Transporters.connect(conf, handler, codec, config.getRemoteHost(), config.getRemotePort(), config.getConnectTimeout());
	}
	
	public boolean isConnected() {
		return client.isConnected();
	}
	
	public void close() {
		client.close();
	}
	
	public void send(Object message) throws RemoteException {
		if (isConnected()) {
			client.send(message);
		}
	}
	
	public void send(int rId,byte[] message) throws RemoteException {
		if (isConnected()) {
			MessageBinWrap binWrap = new MessageBinWrap(rId, message) ;
			client.send(binWrap);
		}
	}
	
	public void send(int rId,IMessage message) throws RemoteException {
		if (isConnected()) {
			MessageObjWrap binWrap = new MessageObjWrap(rId, message) ;
			client.send(binWrap);
		}
	}
}

